#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
#include "contacts.pb.h"

const std::string contacts_file="./contacts.bin";

void AddPeopleInfo(contacts::PeopleInfo* people) {

    std::cout << "-------------新增联系⼈-------------" << std::endl;

    std::cout << "请输入联系人姓名：";
    std::string name;
    std::getline(std::cin, name);
    people->set_name(name);

    std::cout << "请输入联系人年龄：";
    int age;
    std::cin >> age;
    people->set_age(age);

    // 清空输入缓冲区结束条件: 1.清空了 2.清空256字节 3.遇到\n
    std::cin.ignore(256, '\n');

    for(int i=0;;++i) {

        std::cout << "请输入联系人电话" << i+1 << "(只输⼊回⻋完成电话新增):";

        std::string number;
        std::getline(std::cin,number);

        if(number.empty()) {
            break;
        }

        contacts::PeopleInfo_Phone *phone=people->add_phone();
        phone->set_number(number);

    }

    std::cout << "-----------添加联系⼈成功-----------" << std::endl;
}

int main() {

    contacts::Contacts cons;

    // 读取二进制格式文件并进行反序列化
    std::ifstream input(contacts_file,std::ios::in | std::ios::binary);
    if(!input) {

        std::cout << "contacts.bin not find, create new file!" << std::endl;

    } else if(!cons.ParseFromIstream(&input)) { 
    
        std::cerr<<"parse error!"<<std::endl;
        input.close();
        exit(1);

    }   

    // 向通讯录中添加一个联系人
    AddPeopleInfo(cons.add_contacts());

    // 将序列化的对象写入文件
    std::fstream output(contacts_file,std::ios::out | std::ios::binary | std::ios::trunc);
    if(!output.is_open()) {
        std::cerr<<"output open error!"<<std::endl;
        input.close();
        output.close();
        exit(2);
    }

    if(!cons.SerializeToOstream(&output)) {
        std::cerr<<"serialize to ostream error!"<<std::endl;
        input.close();
        output.close();
        exit(3);
    }

    std::cout<<"serialize to ostream success!"<<std::endl;
    input.close();
    output.close();

    return 0;
}

// int main() {

//     std::string people_str;

//     {
//         // 设置属性字段
//         contacts::PeopleInfo people;
//         people.set_name("张三");
//         people.set_age(20);

//         // 序列化
//         if(!people.SerializeToString(&people_str)) {

//             std::cerr<<" 序列化失败! "<<std::endl;
//             exit(1);

//         }

//         // 将序列化的二进制格式数据打印出来
//         std::cout<<" 序列化成功! "<<std::endl \
//                     <<people_str<<std::endl;
//     }

//     {
//         // 反序列化
//         contacts::PeopleInfo people;
//         if(!people.ParseFromString(people_str)) {

//             std::cerr<<" 反序列化失败! "<<std::endl;
//             exit(2);
            
//         }
        
//         // 打印people属性字段
//         std::cout<<" 反序列化成功! "<<std::endl \
//                     <<" name: "<<people.name()<<" age: "<<people.age()<<std::endl;
//     }

//     return 0;
// }